using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using MyUnityLib.Tool;
using YamlDotNet.Serialization;
using System.IO;

namespace ProductExpirationAssistant
{
    /// <summary>下架日期查询记录 数据库</summary>
    public class OffShelfDateQueryDatabase : SingleInstance<OffShelfDateQueryDatabase>
    {
        private const string savePath = "OffShelfDateQueryDatabase.yml";
        private List<OffShelfDateQuery> m_Data;

        public void Init()
        {
            Read();
            Sort();
        }

        public void Add(OffShelfDateQuery query)
        {
            m_Data.Add(query);
            Sort();
            Save();
        }

        public void Remove(OffShelfDateQuery query)
        {
            m_Data.Remove(query);
            Sort();
            Save();
        }

        public void Clear()
        {
            m_Data.Clear();
            Save();
        }

        public OffShelfDateQuery Get(int idx) { return m_Data[idx]; }
        public int Count() { return m_Data.Count; }

        public void Sort()
        {
            m_Data.Sort((OffShelfDateQuery a, OffShelfDateQuery b) => a.Compare(b) ? 1 : -1);
        }

        public void Save()
        {
            string str = new SerializerBuilder().Build().Serialize(m_Data);

            string filePath = Path.Combine(Application.persistentDataPath, savePath);
            try
            {
                File.WriteAllText(filePath, str);
            }
            catch (System.Exception e)
            {
                Debug.LogError(e);
            }
        }
        public void Read()
        {
            string filePath = Path.Combine(Application.persistentDataPath, savePath);
            if (!File.Exists(filePath))
            {
                m_Data = new List<OffShelfDateQuery>();
                return;
            }

            try
            {
                string str = File.ReadAllText(filePath);
                m_Data = new DeserializerBuilder().Build().Deserialize<List<OffShelfDateQuery>>(str);
            }
            catch (System.Exception e)
            {
                Debug.LogError(e);
            }
        }
    }
}